<template>
    <div class="app_container">
        <div class="fl" style="margin-bottom: 10px;" v-if="showBtn">
            <el-button v-role="['/umsMenu/create']" type="primary" @click="openAdd">新增菜单</el-button>
            <el-button v-role="['/umsMenu/create']" type="primary" @click="openAddResources" style="margin-left: 10px;">新增页面功能</el-button>
            <el-button v-role="['/umsMenu/syncMenu']" type="danger" @click="onSyncMenu" style="margin-left: auto;">同步菜单到正式服</el-button>
        </div>

        <!-- 列表 default-expand-all 是否展开 -->
        <el-table :data="tableData" border row-key="id" lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :span-method="arraySpanMethod">
            <el-table-column prop="id" label="菜单id" width="150"></el-table-column>
            <el-table-column label="菜单名称" width="150">
                <template slot-scope="scope">
                    <div v-if="scope.row.resources">功能</div>
                    <div v-else>{{ scope.row.title }}</div>
                </template>
            </el-table-column>
            <el-table-column label="路由路径" width="180">
                <template slot-scope="scope">
                    <div v-if="scope.row.resources"><span style="display: inline-block; width: 100px;">{{ scope.row.title }}</span><span style="margin-left: 30px;">api：{{ scope.row.resources }}</span></div>
                    <div v-else>{{ scope.row.path }}</div>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="redirect" label="重定向" width="180"></el-table-column> -->
            <el-table-column prop="component" label="页面文件路径" width="260"></el-table-column>
            <el-table-column prop="hidden" label="是否显示在侧边栏" width="140">
                <template slot-scope="scope">{{ scope.row.hidden == 1 ? '不显示' : '' }}</template>
            </el-table-column>
            <el-table-column prop="type" label="菜单类型" width="120">
                <template slot-scope="scope">{{ scope.row.type == 'MERCHANT' ? '商家端' : '' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="70">
                <template slot-scope="scope">
                    <el-dropdown placement="bottom-start" @command="openSet">
                        <el-button size="mini" type="primary" icon="el-icon-s-tools"></el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-role="['/umsMenu/update']" :command="{ type: 'edit', item: scope.row }">编辑</el-dropdown-item>
                            <el-dropdown-item v-role="['/umsMenu/delete']" :command="{ type: 'del', item: scope.row }" v-if="showBtn">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <br />

        <!-- 新增弹窗 -->
        <el-dialog :visible.sync="showAdd" title="新增菜单">
            <addMenu :ids="ids" @onCancel="showAdd = false" @onSubmit="onAddSubmit()"></addMenu>
        </el-dialog>
        <!-- 编辑弹窗 -->
        <el-dialog :visible.sync="showEdit" title="编辑菜单">
            <editMenu :editId="editId" @onCancel="showEdit = false" @onSubmit="onEditSubmit()"></editMenu>
        </el-dialog>

        <!-- 新增功能弹窗 -->
        <el-dialog :visible.sync="showAddResources" title="新增功能">
            <addResources :ids="ids" @onCancel="showAddResources = false" @onSubmit="onAddResourcesSubmit()"></addResources>
        </el-dialog>
        <!-- 编辑功能弹窗 -->
        <el-dialog :visible.sync="showEditResources" title="编辑功能">
            <editResources :editId="editId" @onCancel="showEditResources = false" @onSubmit="onEditResourcesSubmit()"></editResources>
        </el-dialog>
    </div>
</template>

<script>
import { apiGetMenuList, apiMenuDel, apiMenuSync } from "@/api/admin.js";
import addMenu from "./addMenu.vue";
import editMenu from "./editMenu.vue";
import addResources from "./addResources.vue";
import editResources from "./editResources.vue";
export default {
    name: 'menu_index',
    components: { addMenu, editMenu, addResources, editResources },
    data() {
        return {
            tableData: [],
            spanRow: [],
            showAdd: false,
            ids: [],
            showEdit: false,
            editId: "",
            showAddResources: false,
            showEditResources: false,
            showBtn: false,
        }
    },
    created() {
        this.getData();
        if (process.env.NODE_ENV != 'production') { //非正式环境显示按钮
            this.showBtn = true
        }
    },
    methods: {
        getData() {
            this.tableData = []
            apiGetMenuList({ pid: 0 }).then(({ data }) => {
                data = data.map((item) => {
                    item.hasChildren = true
                    return item
                })
                data.sort((a, b) => a.sort - b.sort)
                this.tableData = data;
            });
        },
        load(tree, treeNode, resolve) {
            // console.warn('tree', tree);
            apiGetMenuList({ pid: tree.id }).then(({ data }) => {
                data = data.map((item) => {
                    if (item.level < 2) item.hasChildren = true
                    return item
                }).sort((a, b) => { return a.sort - b.sort })
                resolve(data)
                const list = this.tableData;
                _for1: for (let a = 0; a < list.length; a++) {
                    if (list[a].id == tree.id) {
                        list[a].children = data
                        break _for1
                    } else {
                        const list_c = list[a].children || []
                        _for2: for (let b = 0; b < list_c.length; b++) {
                            if (list_c[b].id == tree.id) {
                                list[a].children[b].children = data
                                break _for2
                            }
                        }
                    }
                }
                this.tableData = list
                this.getSpanRow(list)
            });
        },
        // 计算合并行
        getSpanRow(list) {
            // console.warn('list', list);
            const arr = []
            for (let a = 0; a < list.length; a++) {
                arr.push(0)
                const children1 = list[a].children || []
                for (let b = 0; b < children1.length; b++) {
                    arr.push(0)
                    const children2 = children1[b].children || []
                    for (let c = 0; c < children2.length; c++) {
                        if (c == 0) {
                            arr.push(children2.length)
                        } else {
                            arr.push(0)
                        }
                    }
                }
            }
            // console.warn('arr', arr);
            this.spanRow = arr
        },
        // 表格合并列
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (row.resources) {
                if (columnIndex == 1) {
                    return [this.spanRow[rowIndex], 1]
                } else if (columnIndex == 2) {
                    return [1, 4]
                } else if (columnIndex >= 3 && columnIndex <= 5) {
                    return [0, 0]
                }
            }
        },
        // 打开新增弹窗
        openAdd() {
            this.ids = this.tableData.map((item) => ({ id: item.id, name: item.title, sort: item.children?.length }))
            this.showAdd = true;
        },
        onAddSubmit() {
            this.showAdd = false;
            this.getData();
        },
        // 打开新增功能弹窗
        openAddResources() {
            this.ids = this.tableData.map((item) => ({ id: item.id, name: item.title }))
            this.showAddResources = true;
        },
        onAddResourcesSubmit() {
            this.showAddResources = false;
            this.getData();
        },
        // 同步菜单到正式服
        onSyncMenu() {
            this.$msgbox({
                title: '风险操作',
                message: '请确保当前菜单功能全部可用，否则会影响正式环境。确定同步到正式服吗？',
                showCancelButton: true,
                cancelButtonText: '取消',
                confirmButtonText: '确定同步'
            }).then(() => {
                const arr = JSON.parse(JSON.stringify(this.tableData))
                let list = []
                for (let a = 0; a < arr.length; a++) {
                    const item1 = arr[a];
                    list.push(item1)
                    const children1 = item1.children
                    if (children1.length > 0) {
                        for (let b = 0; b < children1.length; b++) {
                            const item2 = children1[b];
                            list.push(item2)
                            const children2 = item2.children
                            if (children2.length > 0) {
                                for (let c = 0; c < children2.length; c++) {
                                    list.push(children2[c])
                                }
                            }
                        }
                    }
                }
                for (let d = 0; d < list.length; d++) {
                    delete list[d].createTime
                    delete list[d].children
                }
                apiMenuSync(list).then((res) => {
                    this.$message({ message: '操作成功', type: 'success' })
                })
            }).catch(() => {
                // 点击取消
            })
        },
        // 设置
        openSet({ type, item }) {
            switch (type) {
                case "edit":
                    this.editId = item.id
                    if (item.resources) {
                        this.showEditResources = true;
                    } else {
                        this.showEdit = true;
                    }
                    break;
                case "del":
                    this.delMenu(item);
                    break;
            }
        },
        // 子组件确认编辑
        onEditSubmit() {
            this.showEdit = false;
            this.getData();
        },
        onEditResourcesSubmit() {
            this.showEditResources = false;
            this.getData();
        },
        delMenu(item) {
            this.$msgbox({
                title: '温馨提示',
                message: `删除${item.resources ? '功能' : '菜单'} ${item.title} ？`,
                showCancelButton: true,
                cancelButtonText: '取消',
                confirmButtonText: '确认'
            }).then(() => {
                apiMenuDel({ ids: [item.id] }).then((res) => {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.getData()
                })
            }).catch(() => {
                // 点击取消
            })
        },

    },
}
</script>

<style></style>